package com.cs.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.cs.constant.RedisConstant;
import com.cs.context.BaseContext;
import com.cs.domain.User;
import com.cs.exception.BaseException;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@CrossOrigin
public class LoginInterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;
    public LoginInterceptor(StringRedisTemplate stringRedisTemplate)
    {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            System.out.println("Method:OPTIONS");
            return true;
        }

        log.info("进入拦截器");
        //1.获取请求头的token
        String header = request.getHeader("Authorization");
        //判断是否为空
        if ( StrUtil.isBlank(header))
        {
            throw new BaseException("请先登录");
        }
        //2.获取用户
        String key = RedisConstant.LOGIN_TOKEN + header;
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
        //3.判断是否存在
        //4.不存在，拦截
        if (entries.isEmpty())
        {
            throw new BaseException("令牌无效");
        }
        //5.存在，转为User对象
        User user = BeanUtil.fillBeanWithMap(entries, new User(), false);
        log.info("{}",user);

        //6.保存到当前线程
        BaseContext.setCurrentId(user.getId());
        //7.刷新有效期
        stringRedisTemplate.expire(RedisConstant.LOGIN_TOKEN + header,
                RedisConstant.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //8.放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
